from config import gl, Config
import traceback
import random
import hashlib
import time
import threading
from bs4 import BeautifulSoup as Soup
import requests
import os
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from urllib import parse

# lock = threading.Lock()


class Words:
    # 这些词语中动词和名词包含其一就能叫出/关闭小微
    call_word = {
        'verb': ['呼叫', '呼唤', '叫出', '滚出来', '打开', '复活'],
        'noun': ['小微', '智障', '沙雕']
    }
    exit_word = {
        'verb': ['滚出去', '滚粗', '爬', '关闭', '推走', '杀死'],
        'noun': ['小微', '智障', '沙雕']
    }
    silent = {
        'verb': ['安静', '捂耳朵', '别说话', '禁言'],
        'noun': ['小微', '智障', '沙雕']
    }
    active = {
        'verb': ['解除禁言', '请说话'],
        'noun': ['小微', '智障', '沙雕']
    }


word_splits = ''' ,;:'"{}[]?，。！？“”；：'''


# return: True/False/None: 进入/出去/没有
def is_moving_me_to(text: str, lock) -> bool or None:
    class UnknownError(Exception):
        pass

    # 处理断句，替换成"."
    for w in word_splits:
        text = text.replace(w, '.')
    splits = text.split('.')
    try:
        # 查看一个短句中有没有关键词
        for s in splits:
            if len(s) < 3:
                continue
            if gl.get_value('running') is None:
                raise UnknownError
            # print('log: running is', gl.get_value('running'))
            if gl.get_value('running'):
                for v in Words.exit_word['verb']:
                    if v in s:
                        for n in Words.exit_word['noun']:
                            if n in s:
                                lock.acquire()
                                gl.set_value('running', False)
                                lock.release()
                                return False
            else:
                for v in Words.call_word['verb']:
                    if v in s:
                        for n in Words.call_word['noun']:
                            if n in s:
                                lock.acquire()
                                gl.set_value('running', True)
                                lock.release()
                                return True
        return None
    except UnknownError:
        traceback.print_exc()
        return None


def is_moving_me_in(text: str) -> bool:
    # 处理断句，替换成"."
    for w in word_splits:
        text = text.replace(w, '.')
    splits = text.split('.')
    try:
        # 查看一个短句中有没有关键词
        for s in splits:
            if len(s) < 3:
                continue
            for v in Words.call_word['verb']:
                if v in s:
                    for n in Words.call_word['noun']:
                        if n in s:
                            return True
        return False
    except Exception:
        traceback.print_exc()
        return False


def roll(probability: float):
    if random.random() < probability:
        return True
    return False


def is_calling_me(text: str) -> bool:
    for w in Config.keywords:
        if w in text:
            return True
    return False


def is_silence_me(text: str, lock) -> bool or None:
    class UnknownError(Exception):
        pass

    # 处理断句，替换成"."
    for w in word_splits:
        text = text.replace(w, '.')
    splits = text.split('.')
    try:
        # 查看一个短句中有没有关键词
        for s in splits:
            if len(s) < 3:
                continue
            if gl.get_value('silence') is None:
                raise UnknownError
            # print('log: silence is', gl.get_value('silence'))
            if gl.get_value('silence'):
                if '@' + Config.nickname in s:
                    lock.acquire()
                    gl.set_value('silence', False)
                    lock.release()
                    return False
                for v in Words.active['verb']:
                    if v in s:
                        for n in Words.active['noun']:
                            if n in s:
                                lock.acquire()
                                gl.set_value('silence', False)
                                lock.release()
                                return False
            else:
                for v in Words.silent['verb']:
                    if v in s:
                        for n in Words.silent['noun']:
                            if n in s:
                                lock.acquire()
                                gl.set_value('silence', True)
                                lock.release()
                                return True
        return None
    except UnknownError:
        traceback.print_exc()
        return None


def uploader(key, data):
    # 上传腾讯云
    bucket = 'bed-1254016670'
    region = 'ap-guangzhou'
    client = CosS3Client(CosConfig(Region=region, SecretId='AKID2sTqzvX7NPCrHRP1RecKn00mJbfUOMQE',
                                   SecretKey='iBOM5Ymk5C5jvsZ0DArITO9euufCamkT'))
    response = client.put_object(Bucket=bucket, Body=data, Key=key)
    print(response)
    # 额外延时，等待图片储存
    time.sleep(1)
    result = 'http://' + bucket + '.cos.ap-guangzhou.myqcloud.com/' + key
    print('result', result)
    return result


def parse_words(text: str) -> str:
    soup = Soup(text, 'html.parser')
    imgs = soup.find_all('img')
    for img in imgs:
        # img.text()
        # print(img.prettify())
        # print(img.get('alt'))
        # print(img.get('src'))
        alt = img.get('alt')
        src = img.get('src')
        if alt is None:
            alt = '[None]'
        if src is None:
            return soup.get_text()
        try:
            data = requests.get(src).content
            filename = hashlib.md5(data).hexdigest() + os.path.splitext(src)[-1] if '.' in src else '.png'
            key = "result/emote_new/%s" % filename
            result = uploader(key, data)
            img.replace_with('![img](%s)' % (result,))
            print(img.prettify())
        except Exception:
            traceback.print_exc()
            return soup.get_text()
    return soup.get_text()


if __name__ == '__main__':
    print(parse_words(
        text='好…好…好久不见<span class="url-icon"><img alt=[抱抱] src="https://h5.sinaimg.cn/m/emoticon/icon/default/d_baobao-820d2c9a0f.png" style="width:1em; height:1em;" /></span>'))
